package com.bjc.platform.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bjc.platform.Constants;
import com.bjc.platform.model.AdmDepartmentType;
import com.bjc.platform.model.AdmOrg;
import com.bjc.platform.model.CustomUserDetails;
import com.bjc.platform.service.AdmOrgService;
import com.bjc.platform.service.IAdmDepartmentTypeService;
import com.bjc.platform.util.ExcelColumnDefinition;
import com.bjc.platform.util.ExcelExporter;
import com.bjc.platform.util.JSONHelper;
import com.bjc.platform.util.Page;
import com.bjc.platform.util.StaticMethod;
import com.bjc.platform.vo.AdmOrgSearchCondition;
import com.bjc.platform.vo.ExtTreeModel;

@Controller
@RequestMapping("/org")
public class AdmOrgController extends BaseController {
	@Autowired
	private AdmOrgService admOrgService;

	@Autowired
	@Qualifier("admDepartmentTypeService")
	private IAdmDepartmentTypeService admDepartmentTypeService;

	@RequestMapping(value = "/query", method = RequestMethod.GET)
	@ResponseBody
	public Object query(@RequestParam("page") int page,
			@RequestParam("start") int start, @RequestParam("limit") int limit,
			@RequestParam HashMap<String, Object> reqParam) throws Exception {

		AdmOrgSearchCondition cond = (AdmOrgSearchCondition) JSONHelper
				.json2Object(String.valueOf(reqParam.get("condition")),
						AdmOrgSearchCondition.class);
		PageRequest pr = new PageRequest(page - 1, limit);
		Page userPage = admOrgService.search(cond, pr);

		return StaticMethod.TOListJSONResult(true, userPage.getResult(),
				userPage.getTotalCount()).getJSONResult();
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Object save(@RequestParam HashMap<String, Object> reqParam) throws Exception {
		AdmOrg org = (AdmOrg) JSONHelper.json2Object(
				JSONHelper.map2json(reqParam), AdmOrg.class);
		// pid 是界面组织树选中的节点
		// 对树做修改时,pid和org.getId值是相同的
		Long pid = StaticMethod.object2Long(reqParam.get("parentOrgTypeId"));
		int subOrgnizeTypeId = StaticMethod.object2Int(reqParam
				.get("subOrgnizeTypeId"));
		int nameCheck = admOrgService.checkOrgName(org.getName(), org.getId(),
				pid);
		int codeCheck = admOrgService.checkOrgCode(org.getCode(), org.getId(),
				pid);

		if (nameCheck != AdmOrgService.VALID_ORG) {
			return StaticMethod.TOJSONResult(true, nameCheck).getJSONResult();
		}
		
		if (codeCheck != AdmOrgService.VALID_ORG) {
			return StaticMethod.TOJSONResult(true, codeCheck).getJSONResult();
		}
		
		AdmDepartmentType depart = admDepartmentTypeService
				.queryOne(subOrgnizeTypeId);
		AdmOrg persist = null;
		AdmOrg parent = admOrgService.get(pid);
		if (org != null && org.getId() != null) {
			persist = admOrgService.get(org.getId());
			persist.setName(org.getName());
			persist.setCode(org.getCode());
			persist.setSetupDate(StaticMethod.object2Date(reqParam.get("setupDate")));
			persist.setContact(org.getContact());
			persist.setContactPhone(org.getContactPhone());
			persist.setAddress(org.getAddress());
			persist.setRemark(org.getRemark());
			persist.setOrgSubType(depart);
			persist.setFlag(true);
			admOrgService.save(persist, parent.getOrgnizeType());
		} else {
			org.setFlag(true);
			org.setParent(parent);
			org.setOrgSubType(depart);
			org.setSetupDate(StaticMethod.object2Date(reqParam.get("setupDate")));
			admOrgService.save(org, parent.getOrgnizeType());
		}
		return StaticMethod.TOJSONResult(true, null).getJSONResult();
	}

	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	@ResponseBody
	public Object delete(@RequestParam HashMap<String, Object> reqParam) {
		Long orgId = StaticMethod.object2Long(reqParam.get("id"));
		// 标记删除
		admOrgService.delete(orgId);

		return StaticMethod.TOJSONResult(true, null).getJSONResult();
	}

	@RequestMapping(value = "/get", method = RequestMethod.GET)
	@ResponseBody
	public Object get(@RequestParam HashMap<String, Object> reqParam) {
		Long orgId = StaticMethod.object2Long(reqParam.get("id"));
		AdmOrg org = admOrgService.getById(orgId);
		return StaticMethod.TOJSONResult(true, org).getJSONResult();
	}

	/**
	 * @param reqParam
	 * @return
	 */
	@RequestMapping(value = "/getTree", method = RequestMethod.GET)
	@ResponseBody
	public Object getTree(@RequestParam HashMap<String, Object> reqParam) {
		
		CustomUserDetails user = StaticMethod.getUser();
		if(user.getOrg() != null && Constants.ORG_GROUP.equals(user.getOrg().getOrgnizeType())){
			// 查询组织结构的树形数据
			List<Map<String, Object>> orgs = admOrgService.getOrgForTree(null);
			ExtTreeModel root = ExtTreeModel.assamblyTreeStructForExt(orgs, false,
					false, true);
			return root;
		}else{
			Long orgId = null;
			if (user.getOrg() != null && user.getOrg().getCompanyId() != null) {
				orgId = user.getOrg().getCompanyId();
			}
			// 查询组织结构的树形数据
			List<Map<String, Object>> orgs = admOrgService.getOrgForTree(orgId);
			ExtTreeModel root = ExtTreeModel.assamblyTreeStructForExt(orgs, false,
					false,true);
			return root;
		}
		
	}

	/**
	 * 查询当前用户的所在公司的组织结构
	 * 
	 * @param reqParam
	 * @return
	 */
	@RequestMapping(value = "/getCompanyTree", method = RequestMethod.GET)
	@ResponseBody
	public Object getCompanyTree(@RequestParam HashMap<String, Object> reqParam) {
		CustomUserDetails user = StaticMethod.getUser();
		Long orgId = null;
		if (user.getOrg() != null && user.getOrg().getCompany() != null) {
			orgId = user.getOrg().getCompany().getId();
		}
		// 查询组织结构的树形数据
		List<Map<String, Object>> orgs = admOrgService.getOrgForTree(orgId);
		ExtTreeModel root = ExtTreeModel.assamblyTreeStructForExt(orgs, false,
				false,true);

		return root;
	}

	/**
	 * 查询当前用户所在组织的结构
	 * 
	 * @param reqParam
	 * @return
	 */
	@RequestMapping(value = "/getOwnTree", method = RequestMethod.GET)
	@ResponseBody
	public Object getOwnTree(@RequestParam HashMap<String, Object> reqParam) {
		CustomUserDetails user = StaticMethod.getUser();
		Long orgId = null;
		if (user.getOrg() != null) {
			orgId = user.getOrg().getId();
		}
		// 查询组织结构的树形数据
		List<Map<String, Object>> orgs = admOrgService.getOrgForTree(orgId);
		ExtTreeModel root = ExtTreeModel.assamblyTreeStructForExt(orgs, false,
				false, true);

		return root;
	}

	/**
	 * 根据查询条件导出用户信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/exportOrg", method = RequestMethod.POST)
	public Object exportOrg(HttpServletRequest request,
			HttpServletResponse response) {
		String orgName = StaticMethod.object2String(request
				.getParameter("name"));
		AdmOrgSearchCondition cond = new AdmOrgSearchCondition();

		if (!StringUtils.isEmpty(orgName)) {
			cond.setName(orgName);
		}

		Page userPage = admOrgService.search(cond, null);
		List<ExcelColumnDefinition> coldfs = new ArrayList<ExcelColumnDefinition>();
		coldfs.add(new ExcelColumnDefinition("name", "组织名称", (short) 3800));
		coldfs.add(new ExcelColumnDefinition("belongOrg", "所属组织",
				(short) 0));
		coldfs.add(new ExcelColumnDefinition("contact", "联系人", (short) 2000));
		coldfs.add(new ExcelColumnDefinition("contactPhone", "联系人电话",
				(short) 3800));
		coldfs.add(new ExcelColumnDefinition("setupDate", "组织成立时间",
				(short) 4600, ExcelExporter.TYPE_DATE, "yyyy-MM-dd"));
		coldfs.add(new ExcelColumnDefinition("orgnizeType", "组织类型",
				(short) 8200));
		try {
			ExcelExporter.export("组织列表", coldfs, userPage.getResult(),
					response, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(value = "/userWarehouses", method = RequestMethod.GET)
	@ResponseBody
	public Object listUserWarehosues(@RequestParam("subType") String subType){
		List<AdmOrg> orgs= this.admOrgService.queryUserOperationOrg(Constants.ORG_DEPARTMENT,new String[]{subType});
		return StaticMethod.TOListJSONResult(true, orgs,orgs.size()).getJSONResult();
	}
	
	@RequestMapping(value = "/userCompanies", method = RequestMethod.GET)
	@ResponseBody
	public Object listUserCompanies(){
		List<AdmOrg> orgs= this.admOrgService.queryUserOperationOrg(Constants.ORG_COMPANY,null);
		return StaticMethod.TOListJSONResult(true, orgs,orgs == null ? 0 : orgs.size()).getJSONResult();
	}
}
